package com.ht.module.file.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;

import com.ht.config.minio.service.MinioService;
import com.ht.config.onlyoffcie.FileConfigDTO;
import com.ht.config.onlyoffcie.FileDocument;
import com.ht.config.onlyoffcie.properties.OnlyProperties;
import com.ht.module.file.entity.FileInfo;
import com.ht.module.file.service.OnlyOfficeService;
import com.ht.module.sys.entity.SysUser;
import com.ht.util.OnlyJwtUtil;
import com.ht.util.UserUtil;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName OnlyOfficeServiceImpl
 * @Description TODO（onlyoffcie）
 * @Author hejialun
 * @Date 2022/8/24 14:32
 * @Version 1.0
 */
@Service
@Slf4j
public class OnlyOfficeServiceImpl implements OnlyOfficeService {
    @Resource
    private OnlyProperties onlyProperties;

    @Resource
    private MinioService minioService;
    @Resource
    private HttpServletRequest request;

    @Override
    public FileConfigDTO buildConfig(FileInfo fileInfo) {
        FileConfigDTO config = new FileConfigDTO().init(onlyProperties,fileInfo);
        //给文档访问接口设置token
        config.getDocument().setUrl(UserUtil.urlSetToken(request,config.getDocument().getUrl()));
        //给回调保存接口设置token
        config.getEditorConfig().setCallbackUrl(UserUtil.urlSetToken(request,config.getEditorConfig().getCallbackUrl()));
        //设置登录用户
        SysUser sysUser = UserUtil.getUser();
        if(BeanUtil.isNotEmpty(sysUser)){
            config.getEditorConfig().getUser().setName(sysUser.getName());
            config.getEditorConfig().getUser().setId(sysUser.getId());
            config.getEditorConfig().getUser().setGroup(sysUser.getId());
        }

        return config;
    }

    @Override
    public void handlerStatus(JSONObject jsonObject) {
        /**
         * 0 - 找不到具有密钥标识符的文档
         * 1 - 正在编辑文档
         * 2 - 文档已准备好保存
         * 3 - 发生文档保存错误
         * 4 - 不作任何更改就关闭文档
         * 6 - 正在编辑文档，但保存当前文档状态
         * 7 - 强制保存文档时发生错误
         */
        int status = jsonObject.getIntValue("status");
        log.info("status[{}]:{}", status, jsonObject);
        String key = jsonObject.getString("key");

        //保存文档-替换删除key
        if (2 == status || 3 == status || 6 == status || 7 == status) {
            //获取文件下载路径
            try {
                String url = jsonObject.getString("url");
                OkHttpClient httpClient = new OkHttpClient();
                //获取源文件路径
                String path = new FileDocument().getPath(key);
                //下载文件
                byte[] bytes = HttpUtil.downloadBytes(url);
                minioService.uploadFileToPath(bytes, path);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                //删除缓存的key
                new FileDocument().delKey(key);
            }

        }
    }

    @Override
    public ModelAndView viewBuild(FileInfo fileInfo, Model model) {
        FileConfigDTO fileConfigDTO = this.buildConfig(fileInfo);
        fileConfigDTO.getDocument().getPermissions().setReview(true);
        fileConfigDTO.getEditorConfig().setMode("view");
        Map<String,Object> map=new HashMap<>();
        map.put("documentType", fileConfigDTO.getDocumentType());
        map.put("type", fileConfigDTO.getType());
        map.put("document", fileConfigDTO.getDocument());
        map.put("editorConfig", fileConfigDTO.getEditorConfig());
        String token = OnlyJwtUtil.createToken(map, onlyProperties.getJwtKey());
        fileConfigDTO.setToken(token);
        String s = JSONObject.toJSONString(fileConfigDTO);
        JSONObject jsonObject = JSONObject.parseObject(s);

        log.info("only office config:" + jsonObject);
        //解决转义问题
        model.addAllAttributes(jsonObject);
        return new ModelAndView("onlyOffice.html");
    }

    @Override
    public ModelAndView editBuild(FileInfo fileInfo, Model model) {
        FileConfigDTO fileConfigDTO = buildConfig(fileInfo);
        fileConfigDTO.getEditorConfig().setMode("edit");
        fileConfigDTO.getDocument().getPermissions().setEdit(true);
        Map<String,Object> map=new HashMap<>();
        map.put("documentType", fileConfigDTO.getDocumentType());
        map.put("type", fileConfigDTO.getType());
        map.put("document", fileConfigDTO.getDocument());
        map.put("editorConfig", fileConfigDTO.getEditorConfig());
        String token = OnlyJwtUtil.createToken(map, onlyProperties.getJwtKey());
        fileConfigDTO.setToken(token);
        String s = JSONObject.toJSONString(fileConfigDTO);
        JSONObject jsonObject = JSONObject.parseObject(s);

        log.info("only office config:" + jsonObject);
        model.addAllAttributes(jsonObject);
        return new ModelAndView("onlyOffice.html");
    }

}

